<template>
	<!-- 首页 -->
	<view class="home">
		<!-- 小程序导航栏 -->
		<u-navbar placeholder>
			<view slot="left" class="iconfont iconqiandao"></view>
			<view slot="center" class="nav-center">
				<u-search 
					placeholder="搜索" 
					v-model="query.title" 
					@search="handleSearch"
					:showAction="false"
				></u-search>
			</view>
			<view slot="right" class="iconfont iconPensyumaobi" @click="handlePublish()"></view>
		</u-navbar>

		<!-- 标签 -->
		<u-sticky bgColor="#fff" v-if="tablist.length">
			<u-tabs 
			    :list="tablist" 
			    :current="tabIndex"
			    lineColor="#01906c" 
			    :activeStyle="{color:'#01906c'}" 
			    :inactiveStyle="{color:'#909399'}" 
			    lineWidth="30"
			    :scrollable="true"
			    @click="changeTab"
			>
			</u-tabs>
		</u-sticky>

		<!-- 列表 -->
		<swiper class="flex-1" :current="swiperIndex" @animationfinish="animationfinish">
			<swiper-item class="h-full" v-for="(item, index) in swiperList" :key="index">
				<scroll-view :ref="'scrollView'+index" :scroll-top="scrollTops[tabIndex]" class="w-full h-full" scroll-y
					@scrolltolower="reachBottom" @scroll="scroll">
					<!-- 有内容 -->
					<template v-if="item.list.length > 0">
						<!-- 资讯列表 -->
						<info-list 
							:item="item1" 
							v-for="(item1,index1) in item.list" 
							:key="index1" 
							:index="index1"
							@mark="handleMark" 
							@follow="handleFollow"
						>
						</info-list>
						<u-loadmore :status="loadStatus[tabIndex]"></u-loadmore>
					</template>
					<!-- 无内容 -->
					<template v-else>
						<u-empty text="本来无一物,何处惹尘埃" icon="/static/img/demo/winter.svg" textSize="16" marginTop='25%'
							mode="list"></u-empty>
					</template>
				</scroll-view>
			</swiper-item>
		</swiper>

		<!-- 回到顶部 -->
		<view v-if="scrollTop[tabIndex] > 400" class="go-top" @click="goTop">
			<u-icon color="#01906c" name="arrow-up" size="24"></u-icon>
		</view>
	</view>
</template>

<script>
import { newsList } from "@/utils/data/data.js";
import InfoList from "@/pages/home/cpns/info-list.vue";
import { UserApi, PostApi,CategoryApi } from '@/api/index.js';
import websocket from '@/utils/websocket/socket';
import websocketMixin from '@/utils/mixins/websocketMixin';

export default {
	mixins: [websocketMixin],
	components: {
		InfoList
	},
	data() {
		return {
			categories: [],
			isLoading: false,
			scrollTops: [0, 0, 0, 0, 0, 0],
			scrollTop: [0, 0, 0, 0, 0, 0],
			loadStatus: ['loadmore', 'loadmore', 'loadmore', 'loadmore', 'loadmore', 'loadmore'],
			tabIndex: 0,
			tablist: [],
			swiperIndex: 0,
			swiperList: newsList.map(tab => ({ list: [] })),
			query: {
				pageNo: 1,
				pageSize: 5,
				title: '',
				categoryName: ''
			}
		};
	},
	onNavigationBarSearchInputClicked() {
		this.handleSearch();
	},
	onNavigationBarButtonTap(e) {
		switch (e.index) {
			case 1:
				this.handlePublish();
				break;
		}
	},
	onLoad() {
		this.getUserId();
		this.getCategories();
		this.resetQuery();
	},
	methods: {
		async getCategories() {
		    const res = await CategoryApi.getCategoriesList();
		    console.log('getCategoriesList 返回结果:', res); // 打印看看结构
		    if (res && res.code === 200) {
		        this.categories = res.data;
	
		        this.tablist = res.data.map(cat => ({
		            name: cat.name.length > 2 ? cat.name.slice(0, 2) : cat.name
		        }));
		        this.swiperList = Array.from({ length: this.tablist.length }, () => ({ list: [] }));
	
		        // 确保在获取到分类后立即加载第一个分类的数据
		        if (this.tablist.length > 0) {
		            await this.changeTab({ index: 0 }); // 主动触发第一个标签页的数据加载
		        }
		    }
		},
		async getUserId() {
			const res = await UserApi.getUserId();
			const app = getApp();
			if (res && res.code === 200) {
				getApp().globalData.userId = res.data;
				uni.setStorageSync('userId', res.data);
				console.log(getApp().globalData.userId);
				websocket.connectSocket(res.data);
			} else {
				console.error('获取用户ID失败');
			}
		},
		handlePublish() {
			this.$u.route('/pages/home/release');
		},
		andleSearch() {
		    if (!this.query.title.trim()) {
		        uni.showToast({ title: '请输入关键词', icon: 'none' });
		        return;
		    }
		
		    // 关键一步：添加当前 tab 的分类名到 query 中
		    this.query.categoryName = this.tablist[this.tabIndex]?.name || '';
		
		    this.resetQuery(); // 重置页码并重新加载数据
		},
		changeTab(item) {
		    this.tabIndex = item.index;
		    this.swiperIndex = item.index;
		    this.query.categoryName = this.tablist[item.index].name; // 同步分类名
		    this.resetQuery(); // 重置页码并重新加载数据
		},
		animationfinish(e) {
		    const index = e.detail.current;
		    this.tabIndex = index;
		    this.swiperIndex = index;
		    this.query.categoryName = this.tablist[index].name; // 同步分类名
		    // 如果你想滑动切换 tab 时也刷新数据，可以取消注释下面这行
		    // this.resetQuery();
		},
		async resetQuery() {
			if (this.isLoading) return; // 防止重复请求
			this.isLoading = true;
	
			this.query.pageNo = 1;
			this.loadStatus.splice(this.tabIndex, 1, 'loading');
			this.swiperList[this.tabIndex].list = []; // 清空当前列表
	
			await this.getList(this.tabIndex);
	
			this.isLoading = false;
		},
		reachBottom() {
			if (this.loadStatus[this.tabIndex] !== 'loadmore') return;
			this.query.pageNo++;
			this.loadStatus.splice(this.tabIndex, 1, 'loading');
			this.getList(this.tabIndex);
		},
		async getList(index) {
			try {
				const res = await PostApi.getAllPosts(this.query);

				if (res && res.code === 200) {
					const list = res.data.list || [];

					// 将接口数据格式转换为 info-list 所需的格式
					const formattedList = list.map(post => ({
						postId: post.postId,
						userId: post.userId,
						username: post.username,
						avatar: post.avatar, // 头像
						title: post.title,     // 标题
						content: post.content, // 正文内容
						comments: post.comments || 0, // 评论数
						views: post.views || 0,     // 浏览数
					}));

					// 合并当前 tab 的数据
					this.$set(this.swiperList[index], 'list', [
						...this.swiperList[index].list,
						...formattedList
					]);

					// 判断是否还有更多数据
					if (list.length < this.query.pageSize) {
						this.loadStatus.splice(index, 1, 'nomore');
					} else {
						this.loadStatus.splice(index, 1, 'loadmore');
					}

					uni.hideLoading();
				} else {
					uni.showToast({ title: '加载失败', icon: 'none' });
					this.loadStatus.splice(index, 1, 'loadmore');
				}
			} catch (err) {
				uni.showToast({ title: '网络异常', icon: 'none' });
				this.loadStatus.splice(index, 1, 'loadmore');
			}
		},
		scroll(e) {
			const index = this.tabIndex;
			this.scrollTop.splice(index, 1, e.detail.scrollTop); // 400显示回到顶部
		},
		goTop() {
			const index = this.tabIndex;
			// 解决view层不同步的问题
			this.scrollTops.splice(index, 1, this.scrollTop[index]);
			this.$nextTick(() => {
				this.scrollTops.splice(index, 1, 0);
				this.scrollTop.splice(index, 1, 0);
			});
		},
		handleMark(item) {
			let infoNum = this.swiperList[this.swiperIndex].list[item.index].infoNum;
			switch (item.value) {
				case 'smile':
					if (infoNum.index == 1) return; // 微笑
					else if (infoNum.index == 2) infoNum.cryNum--;
					infoNum.index = 1;
					infoNum.smileNum++;
					break;
				case 'cry':
					if (infoNum.index == 2) return; // 踩
					else if (infoNum.index == 1) infoNum.smileNum--;
					infoNum.index = 2;
					infoNum.cryNum++;
					break;
			}
			const title = item.value === 'smile' ? '谢谢表扬' : '继续加油';
			uni.showToast({
				title,
				icon: 'none',
			});
		},
	}
};
</script>

<style lang="scss" scoped>
.home {
	display: flex;
	flex-direction: column;
	height: calc(100vh - var(--window-top) - var(--window-bottom)); // 视高 - 内容区顶部 - 内容区底部
	width: 100%;

	/* #ifdef MP-WEIXIN */
	/deep/ .u-navbar {
		.iconfont {
			font-size: 48rpx;
			color: $uni-color-green;
		}

		.u-navbar__content {
			margin-right: 180rpx !important; // 胶囊按钮
		}
	}

	/* #endif */

	.go-top {
		position: fixed;
		right: 30rpx;
		bottom: 100rpx;
		height: 80rpx;
		width: 80rpx;
		background: #E5E7EB;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 100%;
	}
}
</style>